<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <script>
        const PENDING = 'pending';
        const FULFILLED = 'fulfilled';
        const REJECTED = 'rejected';

        class MyPromise {
            constructor(executor) {
                executor(this.resolve, this.reject) // 同步 立即执行
            }
            status = PENDING;
            value = null;
            reason = null;
            // 为什么使用箭头函数
            resolve = (value) => {
                // console.log(this)
                if (this.status === PENDING) {
                    this.status = FULFILLED
                    this.value = value
                }
            }
            reject = (reason) => {
                if (this.status === PENDING) {
                    this.status = REJECTED
                    this.reason = reason
                }
            }
            then(onFulfilled, onRejected) {
                if (this.status === FULFILLED) {
                    onFulfilled(this.value)
                } else if (this.status === REJECTED) {
                    onRejected(this.reason)
                }
            }
        }
        const promise = new MyPromise((resolve, reject) => {
            // 普通函数    
            resolve('success')
            // reject('error')
        })
        // 可选的 2个参数
        promise.then(value => {
            console.log('resolve', value)
        }, reason => {
            console.log('reject', reason)
        })
    </script>
</body>
</html>